package com.sunday.common.mq.kafka.study.spring.e16_Handling_Exceptions;

import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * {@link org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration}
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class MQApi {

    private final Random rand = new Random();

    @Autowired
    private KafkaTemplate<Object, Object> kafkaTemplate;

    @GetMapping("/send/{topic}/{key}")
    public void send(@PathVariable String topic, @PathVariable String key) throws InterruptedException, ExecutionException {
        CompletableFuture<SendResult<Object, Object>> future;
        ValidatedClass validatedClass = new ValidatedClass(rand.nextInt(2));
        log.info("send : {}", validatedClass);
        future = kafkaTemplate.send(topic, key, validatedClass);
        log.info("[send result] : {}", future.get());
    }

    @KafkaListener(
            id = "myId_11",
            topics = "topic11",
            clientIdPrefix = "TEST11",
            errorHandler = "myKafkaListenerErrorHandler"
    )
    public void listen11(@Payload @Valid ValidatedClass validatedClass) {
        log.info("[validatedClass] : {}", validatedClass);
    }

}
